﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;

namespace CoolERP_Common
{
    /// <summary>
    /// 文件管理类
    /// </summary>
    public static class IOHelper
    {
        // 有待完成，目前之处理了 * 的情况
        public static bool FileNameLike(string fileName, string filter)
        {
            if (string.IsNullOrEmpty(filter))
                return true;

            foreach (string pattern in filter.Split(System.IO.Path.PathSeparator))
            {
                if (filter == "*.*")
                    return true;

                string p = pattern.Replace(".", "\\.").Replace("*", ".*");
                Regex r = new Regex(p);
                if (r.IsMatch(fileName))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 用关联程序打开指定的程序或文档
        /// </summary>
        /// <param name="fileName">程序或文档的文件名</param>
        public static void OpenFile(string fileName)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = fileName;
            process.StartInfo.Verb = "Open";
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            process.Start();
        }

        /// <summary>
        /// 获取文件的实际路径，如果路径为映射路径则转换成映射文件指向的路径
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string GetMapPath(string path)
        {
            if (!path.StartsWith(new string(System.IO.Path.DirectorySeparatorChar, 2)))
            {
                var di = new System.IO.DriveInfo(path);
                if (di.DriveType == System.IO.DriveType.Network)
                {
                    var keyNetwork = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Network", false);
                    if (keyNetwork != null)
                    {
                        var keyMap = keyNetwork.OpenSubKey(di.Name.Split(System.IO.Path.VolumeSeparatorChar)[0]);
                        if (keyMap != null)
                        {
                            string remotePath = keyMap.GetValue("RemotePath").ToString();
                            return System.IO.Path.Combine(remotePath, path.Substring(path.IndexOf(System.IO.Path.VolumeSeparatorChar) + 2));
                        }
                    }
                }
            }

            return path;
        }

        /// <summary>
        /// 将数据序列化到文件。
        /// </summary>
        /// <param name="data"></param>
        /// <param name="filePath"></param>
        public static void Serialize(object data, string filePath)
        {
            if (data == null)
            {
                if (File.Exists(filePath))
                    File.Delete(filePath);
            }
            else
            {
                using (Stream stream = new System.IO.FileStream(filePath, FileMode.OpenOrCreate))
                {
                    BinaryFormatter f = new BinaryFormatter();
                    f.Serialize(stream, data);
                }
            }
        }

        /// <summary>
        /// 从文件反序列化数据。
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static object Deserialize(string filePath)
        {
            using (Stream stream = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                BinaryFormatter f = new BinaryFormatter();
                var data = f.Deserialize(stream);
                return data;
            }
        }

        public static T XMLDeserialize<T>(XElement e) where T : class, new()
        {
            if (e == null)
                return new T();

            XmlSerializer sr = new XmlSerializer(typeof(T));
            using (XmlReader r = e.CreateReader())
            {
                return (T)sr.Deserialize(r);
            }
        }

        public static T XMLDeserialize<T>(string xml)
        {
            if (string.IsNullOrEmpty(xml))
                return default(T);

            XmlSerializer sr = new XmlSerializer(typeof(T));
            using (StringReader r = new StringReader(xml))
            {
                return (T)sr.Deserialize(r);
            }
        }

        public static XElement XMLSerialize<T>(T t) where T : class
        {
            if (t == null)
                return null;

            return XElement.Parse(XMLSerializeAsString(t));
        }

        public static string XMLSerializeAsString<T>(T t) where T : class
        {
            if (t == null)
                return null;
            XmlSerializer sr = new XmlSerializer(t.GetType());
            using (StringWriter w = new StringWriter())
            {
                sr.Serialize(w, t);
                return w.ToString();
            }
        }
    }
}
